#include "Scheme/GUIFontManager.h"
#include "Scheme/GUIFont.h"
#include "Scheme/GUIFreeTypeFont.h"
#include "GUILogger.h"

namespace YGUI
{
    template<>
    FontManager* Singleton<FontManager>::m_singleton = NULL;

    FontManager::FontManager(void)
    {
    }

    FontManager::~FontManager(void)
    {
        releaseAllFont();
    }

    Font* FontManager::createFont(const String& name, const String& file_name, const Size<float>& point_sz, 
        unsigned long mode/* = FontStyle::None*/, bool auto_scale/* = false*/, float native_horz_res/* = 800.0f*/, 
        float native_vert_res/* = 600.0f*/, float specific_line_spacing/* = 0.0f*/, bool load_default/* = true*/)
    {
        if(isFontExists(name))
        {
            Logger::getSingleton().printf("FontManager::createFont -- the font with name %s is "
                "aleady exists.\n", name.c_str());
            return NULL;
        }
        FreeTypeFont* fnt = MEMCHECK_NEW FreeTypeFont(name, file_name, point_sz, mode, auto_scale, native_horz_res,
            native_vert_res, specific_line_spacing, load_default);
        m_fonts[name] = fnt;
        return fnt;
    }

    FontManager& FontManager::getSingleton(void)
    {
        static FontManager instance;
        return (*m_singleton);
    }

    FontManager* FontManager::getSingletonPtr(void)
    {
        if(!m_singleton)
            getSingleton();
        return m_singleton;
    }

    void FontManager::releaseFont(const String& name)
    {
        FontDepot::iterator it = m_fonts.find(name);
        if(it != m_fonts.end())
        {
            delete it->second;
            m_fonts.erase(it);
        }
    }

    void FontManager::releaseFont(const Font* fnt)
    {
        if(fnt)
        {
            releaseFont(fnt->getProperty(String("Name")));
        }
    }

    void FontManager::releaseAllFont(void)
    {
        while(m_fonts.size())
        {
            Font* fnt = m_fonts.begin()->second;
            m_fonts.erase(m_fonts.begin());
            delete fnt;
        }
    }

    bool FontManager::isFontExists(const String& name) const
    {
        return (m_fonts.find(name) != m_fonts.end());
    }

    Font* FontManager::getFont(const String& name) const
    {
        FontDepot::const_iterator it = m_fonts.find(name);
        if(it == m_fonts.end())
            return 0;
        return it->second;
    }
};